<template>
  <div>
    <q-card class="full-height q-ml-md" :class="ui.cardClass">
      <q-form @submit="send" class="q-mr-md">
        <br />
        <q-select
          outlined
          v-model="map"
          :use-input="!map"
          :label="$t('StationCalibrate.选择地图')"
          :options="mapList"
          @filter="filterMapFn"
          behavior="menu"
          emit-value
          map-options
          option-label="name"
          option-value="id"
          :rules="[
            (val) =>
              (val && val.length > 0) || $t('StationCalibrate.地图不得为空'),
          ]"
          :dark="ui.isDark"
          readonly
        >
        </q-select>
        <q-select
          outlined
          v-model="moveCmd.content"
          :use-input="!moveCmd.content"
          :label="$t('StationCalibrate.选择导航点')"
          :options="pointList"
          @filter="filterFn"
          behavior="menu"
          emit-value
          map-options
          option-label="name"
          option-value="id"
          :rules="[
            (val) =>
              (val && val.length > 0) || $t('StationCalibrate.导航点不得为空'),
          ]"
          :dark="ui.isDark"
        >
          <template v-slot:after>
            <q-btn
              no-caps
              color="primary"
              :label="$t('StationCalibrate.前往该点')"
              icon="send"
              mapId
              @click="send"
            />
          </template>
        </q-select>
        <q-item-label class="text-subtitle1"
          >{{ $t("StationCalibrate.位置信息") }}：</q-item-label
        >
        <div class="row q-gutter-x-sm">
          <q-input
            :dark="ui.isDark"
            dense
            outlined
            type="tel"
            v-model.number="posture.x"
            class="col"
            label="X"
          />
          <q-input
            :dark="ui.isDark"
            dense
            outlined
            type="tel"
            v-model.number="posture.y"
            class="col"
            label="Y"
          />
          <q-input
            :dark="ui.isDark"
            dense
            outlined
            type="tel"
            v-model.number="posture.z"
            class="col"
            label="Z"
          />
        </div>
        <q-item-label class="text-subtitle1 q-mt-sm"
          >{{ $t("StationCalibrate.角度信息") }}：</q-item-label
        >
        <div class="row q-gutter-x-sm">
          <q-input
            :dark="ui.isDark"
            dense
            outlined
            type="tel"
            v-model.number="posture.qx"
            class="col"
            label="X"
          />
          <q-input
            :dark="ui.isDark"
            dense
            outlined
            type="tel"
            v-model.number="posture.qy"
            class="col"
            label="Y"
          />
          <q-input
            :dark="ui.isDark"
            dense
            outlined
            type="tel"
            v-model.number="posture.qz"
            class="col"
            label="Z"
          />
          <q-input
            :dark="ui.isDark"
            dense
            outlined
            type="tel"
            v-model.number="posture.qw"
            class="col"
            label="W"
          />
        </div>
        <div class="q-gutter-y-sm q-mt-sm">
          <q-btn
            no-caps
            class="full-width text-subtitle1"
            color="primary"
            stretch
            :label="$t('StationCalibrate.获取机器人数据')"
            icon="wifi_protected_setup"
            @click="getStation"
          />
          <transition-flip v-if="moveCmd.content">
            <q-btn
              no-caps
              class="full-width text-subtitle1"
              color="primary"
              stretch
              :label="$t('StationCalibrate.获取该点机器人数据')"
              icon="library_books"
              @click="visible = true"
            />
          </transition-flip>
          <transition-flip v-if="moveCmd.content">
            <q-btn
              no-caps
              class="full-width text-subtitle1"
              color="secondary"
              stretch
              :label="
                posture.id
                  ? $t('StationCalibrate.修改数据')
                  : $t('StationCalibrate.保存数据')
              "
              icon="save"
              @click="save"
            />
          </transition-flip>
        </div>
      </q-form>
    </q-card>
    <q-dialog v-model="visible">
      <q-card style="min-width: 15rem" :class="ui.cardClass">
        <q-card-section class="q-px-md text-h6">
          {{ $t("StationCalibrate.选择设备") }}
        </q-card-section>
        <q-separator :dark="ui.isDark" />
        <q-card-section>
          <q-select
            :dark="ui.isDark"
            outlined
            v-model="onDevice"
            :label="$t('StationCalibrate.选择设备')"
            :options="deviceOptions"
          />
        </q-card-section>
        <q-btn
          no-caps
          :label="$t('BoundManage.确认')"
          :class="ui.btnClass"
          class="full-width"
          @click="getDevicePosture(onDevice)"
          v-if="onDevice"
        />
      </q-card>
    </q-dialog>
  </div>
</template>
<script setup>
import { useUiStore } from "stores/ui";
import { computed, onMounted, ref, watch } from "vue";
import { api } from "boot/axios";
import { useAPIStore } from "stores/api";
import { useQuasar } from "quasar";
import { useI18n } from "vue-i18n";
import TransitionFlip from "components/animations/Flip.vue";

const props = defineProps({
  // 地图Id
  mapId: { type: String, default: "" },
  // 机器人ID
  deviceId: { type: String, default: "" },
  poseId: { type: String, default: "" },
});
const $t = useI18n().t;
const $q = useQuasar();
const ui = useUiStore();
const moveCmd = ref({
  // 指令实体
  type: "move-basic",
  content: "",
  device: props.deviceId,
});
const posture = ref({});
const poseId = computed(() => props.poseId);
const mapId = computed(() => props.mapId);
const mapPoseId = computed(() => moveCmd.value.content);
const pointList = ref([]); // 导航列表
const pointOldList = ref([]); // 旧导航列表
const mapList = ref([]); // 地图列表
const mapOldList = ref([]); // 旧地图列表
const map = ref("");
const visible = ref(false); // 是否显示机器人
const deviceOptions = ref([]); // 当前点有数据的机器人
const onDevice = ref(""); // 选中需要复制的机器人

onMounted(() => {
  map.value = props.mapId;
  getPoint();
  getMap();
});
watch(visible, (value) => {
  if (!visible.value) {
    onDevice.value = "";
  }
});
watch(mapId, (value) => {
  map.value = props.mapId;
});
watch(poseId, (value) => {
  moveCmd.value.content = value;
});
watch(mapPoseId, (value) => {
  posture.value = {};
  onDevice.value = "";
  getCalibration(value);
  getDevice(value);
});
watch(map, (value) => {
  getPoint();
});

// 获取当前点当前设备是否有数据
function getCalibration(id) {
  api
    .get(useAPIStore().mapUrl + "calibration", {
      params: { robotId: props.deviceId, mapPoseId: id },
    })
    .then((rs) => {
      if (rs.data.code === 200) {
        $q.notify({
          type: "positive",
          message: $t("StationCalibrate.获取信息成功"),
        });
        posture.value = rs.data.data;
      }
    });
}
// 获取当前点上绑定的机器人
function getDevice(id) {
  api
    .get(useAPIStore().mapUrl + "calibration/robots", {
      params: { mapPoseId: id },
    })
    .then((rs) => {
      if (rs.data.code === 200) {
        deviceOptions.value = rs.data.data;
        deviceOptions.value = deviceOptions.value.filter(
          (item) => item !== props.deviceId
        );
      }
    });
}
// 获取当个点位上的机器人列表
function getDevicePosture(deviceId) {
  api
    .get(useAPIStore().mapUrl + "calibration", {
      params: { robotId: deviceId, mapPoseId: mapPoseId.value },
    })
    .then((rs) => {
      if (rs.data.code === 200) {
        $q.notify({
          type: "positive",
          message: $t("StationCalibrate.获取信息成功"),
        });
        posture.value.frameID = rs.data.data.frameID;
        posture.value.seq = rs.data.data.seq;
        posture.value.qw = rs.data.data.qw;
        posture.value.qx = rs.data.data.qx;
        posture.value.qy = rs.data.data.qy;
        posture.value.qz = rs.data.data.qz;
        posture.value.x = rs.data.data.x;
        posture.value.y = rs.data.data.y;
        posture.value.z = rs.data.data.z;
        visible.value = false;
      } else {
        $q.notify({
          type: "negative",
          message: $t("StationCalibrate.获取信息失败"),
        });
      }
    });
}
// 获取地图列表
function getMap() {
  // 根据地图id获取点位信息
  api.get(useAPIStore().mapUrl + "new/map/all/simple?type=ros").then((res) => {
    if (res.data.code === 200) {
      mapList.value = res.data.data;
      mapOldList.value = mapList.value;
    }
  });
}
// 获取点位列表
function getPoint() {
  // 根据地图id获取点位信息
  api
    .get(useAPIStore().mapUrl + "mapPose/ros/mapID/" + map.value)
    .then((res) => {
      pointList.value = res.data;
      pointOldList.value = pointList.value;
    });
}
// 过滤筛选点位
function filterFn(val, update) {
  // 如果值等于空时还原列表
  if (val === "") {
    update(() => {
      pointList.value = pointOldList.value;
    });
    return;
  }
  update(() => {
    // toLowerCase() 方法用于把字符串转换为小写
    const needle = val.toLowerCase();
    // 过滤出符合条件的
    pointList.value = pointOldList.value.filter(
      (v) => v.name.toLowerCase().indexOf(needle) > -1
    );
  });
}
// 过滤筛选地图
function filterMapFn(val, update) {
  // 如果值等于空时还原列表
  if (val === "") {
    update(() => {
      mapList.value = mapOldList.value;
    });
    return;
  }
  update(() => {
    // toLowerCase() 方法用于把字符串转换为小写
    const needle = val.toLowerCase();
    // 过滤出符合条件的
    mapList.value = mapOldList.value.filter(
      (v) => v.name.toLowerCase().indexOf(needle) > -1
    );
  });
}
// 执行导航指令
function send() {
  $q.dialog({
    title: $t("StationCalibrate.执行到当前点"),
    message: $t("StationCalibrate.选择运动模式"),
    cancel: $t("StationCalibrate.取消"),
    ok: $t("StationCalibrate.确认"),
    options: {
      type: "radio",
      model: "move-basic",
      items: [
        { label: $t("StationCalibrate.普通移动"), value: "move-basic" },
        { label: $t("StationCalibrate.带方向导航"), value: "move-directional" },
        { label: $t("StationCalibrate.直线行驶"), value: "move-straight" },
      ],
    },
    dark: ui.isDark,
    persistent: true,
  }).onOk(() => {
    api
      .post(
        useAPIStore().centerUrl + "center/send/" + moveCmd.value.device,
        moveCmd.value
      )
      .then((rs) => {
        if (rs.data === "done") {
          $q.notify({
            type: "positive",
            message: $t("StationCalibrate.指令已下发"),
          });
        }
      })
      .catch(() => {
        $q.notify({
          message: $t("StationCalibrate.接口请求异常"),
          type: "negative",
        });
      });
  });
}
// 保存工位信息
function save() {
  if (posture.value.id) {
    api
      .put(useAPIStore().mapUrl + "calibration", posture.value)
      .then((rs) => {
        if (rs.data.code === 200) {
          $q.notify({
            type: "positive",
            message: $t("StationCalibrate.修改成功"),
          });
        } else {
          $q.notify({
            type: "negative",
            message: $t("StationCalibrate.修改失败"),
          });
        }
      })
      .catch(() => {
        $q.notify({
          type: "negative",
          message: $t("StationCalibrate.接口请求异常"),
        });
      });
  } else {
    posture.value.robotId = props.deviceId;
    posture.value.mapPoseId = mapPoseId.value;
    api
      .post(useAPIStore().mapUrl + "calibration", posture.value)
      .then((rs) => {
        if (rs.data.code === 200) {
          $q.notify({
            type: "positive",
            message: $t("StationCalibrate.保存成功"),
          });
          posture.value.id = rs.data.data.id;
          getDevice(mapPoseId.value);
        } else {
          $q.notify({
            type: "negative",
            message: $t("StationCalibrate.保存失败"),
          });
        }
      })
      .catch(() => {
        $q.notify({
          type: "negative",
          message: $t("StationCalibrate.接口请求异常"),
        });
      });
  }
}
// 获取机器人身上当前的数据
function getStation() {
  api
    .post(useAPIStore().amrUrl + "ros/call", [], {
      params: { service: "/dm_code_calibration_pose" },
    })
    .then((rs) => {
      const pose = JSON.parse(rs.data.values.message);
      console.log(pose.frame_id);
      posture.value.frameId = pose.frame_id;
      posture.value.seq = pose.seq;
      posture.value.qw = pose.qw;
      posture.value.qx = pose.qx;
      posture.value.qy = pose.qy;
      posture.value.qz = pose.qz;
      posture.value.x = pose.x;
      posture.value.y = pose.y;
      posture.value.z = pose.z;
    })
    .then(() => {
      $q.notify({
        type: "positive",
        message: $t("StationCalibrate.获取信息成功"),
      });
    })
    .catch(() => {
      $q.notify({
        type: "negative",
        message: $t("StationCalibrate.获取信息失败"),
      });
    });
}
</script>
<style scoped></style>
